<template>
  <div class="app-container">
    <el-form
        ref="queryRef"
        :model="queryForm"
        :inline="true"
    >
      <el-form-item label="部门名称" prop="deptName">
        <el-input
            v-model="queryForm.deptName"
            placeholder="请输入部门名称"
            clearable
            @keyup.enter="handleQuery()"
            @clear="handleQuery()"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
            v-model="queryForm.status"
            placeholder="部门状态"
            clearable
            @change="handleQuery()">
          <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <!-- prettier-ignore -->
        <el-button icon="Refresh" @click="resetClick()">重置</el-button>
        <!-- prettier-ignore -->
        <el-button type="primary" @click="handleQuery()">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            size="small"
            @click="handleAdd"
        >新增
        </el-button
        >
      </el-col>

    </el-row>

    <el-table
        border
        stripe
        :data="deptList"
        row-key="deptId"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="deptName" label="部门名称"/>
      <!-- prettier-ignore -->
      <el-table-column prop="deptId" label="编号" align="left" width="200"/>
      <el-table-column prop="orderNum" label="排序"/>
      <el-table-column prop="status" label="状态">

      </el-table-column>
      <el-table-column
          label="创建日期"
          align="center"
          prop="createTime"
          width="300"
      >
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="修改日期"
          align="center"
          prop="updateTime"
          width="300"
      >

      </el-table-column>
      <el-table-column
          label="操作"
          align="center"
          width="300"
          class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-link
              class="table_link_btn"
              :underline="false"
              type="primary"
              @click="handleUpdate(scope.row)"
          ><span class="table_link_text">修改</span></el-link
          >
          <el-link
              class="table_link_btn"
              :underline="false"
              type="primary"
              @click="handleAdd(scope.row)"
          ><span class="table_link_text">新增</span></el-link
          >
          <el-link
              class="table_link_btn"
              :underline="false"
              v-if="scope.row.parentId != 0"
              type="danger"
              @click="handleDelete(scope.row)"
          ><span class="table_link_text">删除</span></el-link
          >
        </template>
      </el-table-column>
    </el-table>


    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" v-model="open" width="30%" append-to-body>
      <el-form
          ref="deptRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <!-- prettier-ignore -->
              <el-tree-select
                  v-model="form.parentId"
                  :data="deptOptions"
                  :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                  value-key="deptId"
                  placeholder="选择上级部门"
                  check-strictly
                  filterable
                  :render-after-expand="false"
                  style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input
                  v-model="form.deptName"
                  placeholder="请输入部门名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number
                  v-model="form.orderNum"
                  controls-position="right"
                  :min="0"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input
                  v-model="form.leader"
                  placeholder="请输入负责人"
                  maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                  v-model="form.phone"
                  placeholder="请输入联系电话"
                  maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                  v-model="form.email"
                  placeholder="请输入邮箱"
                  maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in statusOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                >{{ dict.label }}
                </el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!-- prettier-ignore -->
          <el-button type="primary" @click="submitForm()">确 定</el-button>
          <el-button @click="cancel()">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from "vue";
import {addDateRange, handleTree, resetForm} from "@/utils/z.ts";
import {
  addDept,
  delDept,
  getDept,
  listDept,
  listDeptExcludeChild,
  updateDept
} from "@/api/system/dept.ts";
import {ElForm, ElMessage, ElMessageBox} from "element-plus";

const form = ref<any>();
const queryForm = ref<any>({
  deptName: undefined,
  status: undefined,
});
// 状态数据字典
const statusOptions = ref<any>([
  {
    value: "0",
    label: "正常",
  }, {
    value: "1",
    label: "停用",
  },
]);
const deptRef = ref<InstanceType<typeof ElForm>>();
const queryRef = ref<InstanceType<typeof ElForm>>();
const rules = ref<any>({
  parentId: [
    {required: true, message: "上级部门不能为空", trigger: "blur"},
  ],
  deptName: [
    {required: true, message: "部门名称不能为空", trigger: "blur"},
  ],
  orderNum: [
    {required: true, message: "显示排序不能为空", trigger: "blur"},
  ],
  email: [
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
  phone: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});
// 选中数组
const ids = ref<any>([]);
const deptList = ref<any>();
const open = ref<boolean>(false);
const title = ref<string>("");
const deptOptions = ref<any>();
const isExpandAll = ref<boolean>(true);

onMounted(() => {
  getList();

});
const resetClick = () => {
  getList()
}
const handleQuery = () => {
  getList()
}

const getList = () => {
  listDept(queryForm.value).then(
      (response: any) => {
        deptList.value = handleTree(response.data, "deptId");

      }
  );
}


/** 重置按钮操作 */
const resetQuery = () => {
  resetForm(queryRef);
  handleQuery();
};
/** 新增按钮操作 */
const handleAdd = async (row: any) => {
  reset();
  await listDept().then((response: any) => {
    if (response.code === 200) {
      deptOptions.value = handleTree(response.data, "deptId");
    }
  });
  if (row != undefined) {
    form.value.parentId = row.deptId;
  }
  title.value = "添加部门";
  open.value = true;
};
/** 表单重置 */
const reset = () => {
  form.value = {
    deptId: undefined,
    parentId: undefined,
    deptName: undefined,
    orderNum: 0,
    leader: undefined,
    phone: undefined,
    email: undefined,
    status: "0",
  };
  resetForm(deptRef);
};

/** 修改按钮操作 */
const handleUpdate = async (row: any) => {
  const deptId = row.deptId || ids.value[0];
  reset();
  await listDeptExcludeChild(deptId).then((response: any) => {
    if (response.code === 200) {
      deptOptions.value = handleTree(response.data, "deptId");
    }
  });
  await getDept(deptId).then((response: any) => {
    if (response.code === 200) {
      const data = response.data;
      data.orderNum = parseInt(data.orderNum);
      // 修复顶级父部门显示为0的问题
      if (data.parentId === "0") {
        data.parentId = parseInt(data.parentId);
      }
      form.value = data;
      title.value = "修改部门";
      open.value = true;
    }
  });
};
/** 删除按钮操作 */
const handleDelete = (row: any) => {
  // 设置当前行被选中
  ElMessageBox.confirm('是否确认删除名称为"' + row.deptName + '"的数据项?')
      .then(() => {
        return delDept(row.deptId);
      })
      .then((response: any) => {
        if (response.code === 200) {
          ElMessage({message: "删除成功", type: 'success'})
          getList();
        }
      })
      .catch(() => {
        console.log("取消了删除");
      });
};
/** 提交按钮 */
const submitForm = async () => {
  await deptRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.deptId !== undefined) {
        updateDept(form.value).then((response: any) => {
          if (response.code === 200) {
            ElMessage({message: "修改成功", type: 'success'})
            open.value = false;
            handleQuery();
          }
        });
      } else {
        addDept(form.value).then((response: any) => {
          if (response.code === 200) {
            ElMessage({message: "新增成功", type: 'success'})
            open.value = false;
            handleQuery();
          }
        });
      }
    }
  });
};

</script>


<style scoped>

</style>
